var redis = require('redis');
var config = require('config').get('redis');//require('../config/config.json').redis;
var client = redis.createClient(config.port, config.host);

var bcrypt = require('bcryptjs');
var db = {};

const USER = 'USER: ';
const AT = 'AT: ';
const UI = 'UI: ';
const LINK = 'LINK: ';

client.on('connect', function() {
	console.log('Redis is connected');
	init();
});

client.on('end', function() {
	console.log('Redis is disconnected');
});

client.on('error', function(err) {
	console.log('Error ' + err);
});

db.putUser = function(user, cb) {
	cb = cb || show;
	console.log(USER + user.username)
	client.hmset(USER + user.username, user, cb);
	//client.expire(USER + user.username, 3 * 60 * 60);
}

db.delUser = function(username, cb) {
	cb = cb || show;
	client.del(USER + username, cb);
}

db.getUser = function(at, cb) {
	cb = cb || show;
	client.hgetall(USER + at, cb);
}

db.putAt = function(at, cb) {
	cb = cb || show;
	client.hmset(AT + at.token, at, cb);
	console.log(now() + 3 * 60 * 60)
	client.expireat(AT + at.token, now() + 3 * 60 * 60);
}

db.delAt = function(token, cb) {
	cb = cb || show;
	client.del(AT + token, cb);
}

db.getAt = function(token, cb) {
	cb = cb || show;
	client.hgetall(AT + token, cb);
}

db.linkUserToAt = function(username, token, cb) {
	cb = cb || show;
	console.log("link is running")
	client.set(LINK + username, token, cb);
	client.expireat(LINK + username, now() + 3 * 60 * 60);
}

db.islinkExisted = function(username, cb) {
	cb = cb || show;
	client.get(LINK + username, cb);
}

db.delLink = function(username, cb) {
	cb = cb || show;
	client.del(LINK + username, cb);
}

function now(){
	return parseInt((+new Date)/1000);
}

function show(err, reply){
	//redis.print(err, reply);
}
function init() {
	db.putUser({username: 'bitch', password: bcrypt.hashSync('111111', 8), nickname: 'bb', role: 'user', age: 19, icon: '1502180763666.jpg'});
	db.putUser({username: 'sam', password: bcrypt.hashSync('111111', 8), nickname: 'Sam', role: 'admin', age: 20, icon: '1502182468981.jpg'});
	db.putUser({username: 'visitor', password: bcrypt.hashSync('111111', 8), nickname: 'Visitor', role: 'admin', age: 21, icon: '1502182704712.png'});
}

module.exports = db;